package org.asiainfo.auth.listener;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.asiainfo.common.core.constant.CacheConstants;
import org.asiainfo.common.core.constant.CacheNames;
import org.asiainfo.common.core.constant.Constants;
import org.asiainfo.common.core.utils.MessageUtils;
import org.asiainfo.common.core.utils.ServletUtils;
import org.asiainfo.common.core.utils.SpringUtils;
import org.asiainfo.common.core.utils.ip.AddressUtils;
import org.asiainfo.common.log.event.LoginInfoEvent;
import org.asiainfo.common.redis.utils.RedisUtils;
import org.asiainfo.system.api.RemoteUserService;
import org.asiainfo.system.api.domain.SysUserOnline;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 用户行为监听
 *
 * @author dotor-ww
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class UserActionListener implements SaTokenListener {

    @DubboReference
    private RemoteUserService remoteUserService;

    private final SaTokenConfig saTokenConfig;

    /**
     * 每次登录时触发
     *
     * @param loginType  账号类别
     * @param loginId    账号id
     * @param tokenValue 本次登录产生的 token 值
     * @param loginModel 登录参数
     */
    @Override
    public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginModel loginModel) {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = ServletUtils.getClientIP();
        SysUserOnline userOnline = new SysUserOnline();
        userOnline.setIpaddr(ip);
        userOnline.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        userOnline.setBrowser(userAgent.getBrowser().getName());
        userOnline.setOs(userAgent.getOs().getName());
        userOnline.setLoginTime(System.currentTimeMillis());
        userOnline.setTokenId(tokenValue);
        String username = (String) loginModel.getExtra(CacheNames.USER_NAME_KEY);
        Long tenantId = (Long) loginModel.getExtra(CacheNames.TENANT_KEY);
        userOnline.setUserName(username);
        userOnline.setClientKey((String) loginModel.getExtra(CacheNames.CLIENT_KEY));
        userOnline.setDeviceType(loginModel.getDevice());
        userOnline.setDeptName((String) loginModel.getExtra(CacheNames.DEPT_NAME_KEY));
        if (saTokenConfig.getTimeout() == -1) {
            RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, userOnline);
        } else {
            RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, userOnline, Duration.ofSeconds(saTokenConfig.getTimeout()));
        }
        // 记录登录日志
        LoginInfoEvent loginInfoEvent = new LoginInfoEvent();
        loginInfoEvent.setTenantId(tenantId);
        loginInfoEvent.setUsername(username);
        loginInfoEvent.setStatus(Constants.LOGIN_SUCCESS);
        loginInfoEvent.setMessage(MessageUtils.message("user.login.success"));
        loginInfoEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(loginInfoEvent);
        // 更新登录信息
        remoteUserService.recordLoginInfo((Long) loginModel.getExtra(CacheNames.USER_KEY), tenantId, ip);
        log.info("用户登录, 用户ID:{}, 用户token:{}", loginId, tokenValue);
    }

    /**
     * 每次注销时触发
     *
     * @param loginType  账号类别
     * @param loginId    账号id
     * @param tokenValue token值
     */
    @Override
    public void doLogout(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("用户退出, 用户Id:{}, 用户Token:{}", loginId, tokenValue);
    }

    /**
     * 每次被踢下线时触发
     *
     * @param loginType  账号类别
     * @param loginId    账号id
     * @param tokenValue token值
     */
    @Override
    public void doKickout(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("用户被踢下线, 用户Id:{}, 用户Token:{}", loginId, tokenValue);
    }

    /**
     * 每次被顶下线时触发
     *
     * @param loginType  账号类别
     * @param loginId    账号id
     * @param tokenValue token值
     */
    @Override
    public void doReplaced(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("用户被顶下线, 用户Id:{}, 用户Token:{}", loginId, tokenValue);
    }

    /**
     * 每次被封禁时触发
     *
     * @param loginType   账号类别
     * @param loginId     账号id
     * @param service     指定服务
     * @param level       封禁等级
     * @param disableTime 封禁时长，单位: 秒
     */
    @Override
    public void doDisable(String loginType, Object loginId, String service, int level, long disableTime) {

    }

    /**
     * 每次被解封时触发
     *
     * @param loginType 账号类别
     * @param loginId   账号id
     * @param service   指定服务
     */
    @Override
    public void doUntieDisable(String loginType, Object loginId, String service) {

    }

    /**
     * 每次打开二级认证时触发
     *
     * @param loginType  账号类别
     * @param tokenValue token值
     * @param service    指定服务
     * @param safeTime   认证时间，单位：秒
     */
    @Override
    public void doOpenSafe(String loginType, String tokenValue, String service, long safeTime) {

    }

    /**
     * 每次关闭二级认证时触发
     *
     * @param loginType  账号类别
     * @param tokenValue token值
     * @param service    指定服务
     */
    @Override
    public void doCloseSafe(String loginType, String tokenValue, String service) {

    }

    /**
     * 每次创建 SaSession 时触发
     *
     * @param id SessionId
     */
    @Override
    public void doCreateSession(String id) {

    }

    /**
     * 每次注销 SaSession 时触发
     *
     * @param id SessionId
     */
    @Override
    public void doLogoutSession(String id) {

    }

    /**
     * 每次 Token 续期时触发（注意：是 timeout 续期，而不是 active-timeout 续期）
     *
     * @param tokenValue token 值
     * @param loginId    账号id
     * @param timeout    续期时间
     */
    @Override
    public void doRenewTimeout(String tokenValue, Object loginId, long timeout) {

    }
}
